import win32gui, win32con, pyautogui, json
from pynput import mouse
from pynput import keyboard
import win32con, win32print
import win32api

def find_window_by_title(window_title):
  """根据窗口标题寻找窗口句柄"""
  hwnd = win32gui.FindWindow(None, window_title)
  return hwnd

# def get_screen_size_real():
#     return pyautogui.size()

# def get_screen_size_fake():
#     return win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)

# def get_true_rect(hwnd):
#     left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    
#     w, h = get_screen_size_real()
#     fake_w, fake_h = get_screen_size_fake()
#     zoom = w / fake_w
#     return left*zoom, top*zoom, right*zoom, bottom*zoom

def task():

    # hwnd_by_title = find_window_by_title(target_title)
    # if hwnd_by_title:
    #     print(f"找到标题为'{target_title}'的窗口句柄：{hwnd_by_title}")
    # else:
    #     raise Exception(f"未找到标题为'{target_title}'的窗口。")

    # left, top, right, bottom = get_true_rect(hwnd_by_title)
    # print(f'窗口参数:\n  left: {left}\n  top: {top}\n  right: {right}\n  bottom: {bottom}\n')

    # win32gui.SendMessage(hwnd_by_title, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
    # pyautogui.press("alt")
    # win32gui.SetForegroundWindow(hwnd_by_title)

    points = []

    mlistener = mouse.Listener()
    kblistener = keyboard.Listener()

    def on_click(x: int, y: int, button, pressed):
        hwnd = win32gui.GetForegroundWindow()  # 获取前台窗口句柄
        window_title = win32gui.GetWindowText(hwnd)  # 获取窗口的标题（名称）
        if pressed:
            screen_w, screen_h = pyautogui.size()
            window_l, window_t, window_r, window_b = win32gui.GetWindowRect(hwnd)
            window_w = window_r - window_l
            window_h = window_b - window_t
            points.append({
                'windowname': window_title,
                'screensize': {
                    'width': screen_w,
                    'height': screen_h,
                },
                'globalposition': {
                    'x': x, 'y': y
                },
                'windowposition': {
                    'x': window_l, 'y': window_t
                },
                'windowsize': {
                    'width': window_w,
                    'height': window_h,
                }
            })
        kblistener.stop()
        return False
    def cancel_on_esc(key: keyboard.Key):
        if key == keyboard.Key.esc:
            mlistener.stop()
        return False
    
    mlistener = mouse.Listener(on_click=on_click)
    mlistener.start()
    
    kblistener = keyboard.Listener(on_press=cancel_on_esc)
    kblistener.start()

    kblistener.join()
    
    return json.dumps(points[0], ensure_ascii=False)